package corej.prj.chatRoom.huxz;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class ChatClientHuxz {
    private JFrame frame;

    private JTextArea jta;

    private JTextField jtf;

    private Socket s;

    private BufferedReader in;

    private PrintWriter out;

    public void init() {
        // -------------------ѡ������---------------------
        frame = new JFrame("Huxz");
        frame.setSize(300, 250);
        // -------------------ѡ�񲼾ֹ�����-----------------
        LayoutManager lmanager = new BorderLayout();
        frame.setLayout(lmanager);
        frame.addWindowListener(new WindowAdapter() {

            /*
                * (non-Javadoc)
                *
                * @see java.awt.event.WindowAdapter#windowClosing(java.awt.event.WindowEvent)
                */
            @Override
            public void windowClosing(WindowEvent e) {
                frame.dispose();
                System.exit(0);
            }

        });
        // ----------------������----------------
        jta = new JTextArea();
        frame.add(new JScrollPane(jta));
        jtf = new JTextField();
        frame.add(jtf, "South");

        jta.setEditable(false);
        // frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        // 2.init Socket and Stream
        try {
            s = new Socket("localhost", 9000);
            out = new PrintWriter(s.getOutputStream());
            in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 3.add ActionListener
        jtf.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String text = jtf.getText();
                jtf.setText("");
                out.println(text);
                out.flush();
            }
        });
    }

    private void receive() {
        try {
            while (true) {
                // �оͶc�û�о�����
                String str = in.readLine();
                jta.append(str + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // ������
    public ChatClientHuxz() {
        init();
        receive();
    }

    public static void main(String[] args) {
        new ChatClientHuxz();
    }

}
